package com.zz.wechat.controller;

import com.zz.exception.DataValidationException;
import com.zz.form.MessageForm;
import com.zz.util.ResultVOUtil;
import com.zz.vo.ResultVO;
import com.zz.wechat.util.*;

import lombok.extern.slf4j.Slf4j;
import org.dom4j.DocumentException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Bsea
 * 2019-06-1
 */
@RequestMapping("/wechat")
@Slf4j
@RestController
public class WechatController {
    @Resource
    MessageTool messageTool;



    //发送模板消息
    @PostMapping("/sendMessage")
    public ResultVO<Map<String, String>> sendMsg(@Valid MessageForm messageForm, BindingResult bindingResult) throws IOException {
        log.info(messageForm.toString());

        if (bindingResult.hasErrors()) {
            log.error("发送微信模板消息参数不正确, sendMsg");
            throw new DataValidationException(bindingResult.getFieldError().getDefaultMessage());
        }
        //"尊敬的***,请于2019年06月12日，上午9点到11点参加关于力促乡村振兴工作会议"
        String message="尊敬的"+messageForm.getUsername()+"请于"+messageForm.getMeetingdate()+"参加"+messageForm.getTitle();
        messageTool.sendMsg(messageForm.getOpenid(),"",message,"");
        Map<String, String> map = new HashMap<>();
        map.put("rs", "Y");

        return ResultVOUtil.success(map);
    }




    @GetMapping("/int")
    public String intWeichat(HttpServletRequest req){
        String token=WeiChatConfig.TOKEN;
        String signature=req.getParameter("signature");
        String timestamp=req.getParameter("timestamp");
        String nonce=req.getParameter("nonce");
        String param4=req.getParameter("echostr");

        log.info("initWeiChat timestamp="+timestamp);
        log.info("initWeiChat nonce="+nonce);
        log.info("initWeiChat signature="+signature);
        log.info("initWeiChat echostr="+param4);
        boolean result=false;
        try {
            if(signature.equals(WeiChatUtil.getSHA1(token, timestamp, nonce))){
                result=true;

            };
        } catch (AesException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        if(result){
            return param4;

        }else{

            return "error";
        }
    }


    /*
     * 1. 接收用户给微信公众平台发的消息
     *
     */

    @RequestMapping(value="int" ,method= RequestMethod.POST)
    public String message(HttpServletRequest req, HttpServletResponse response) throws IOException, DocumentException {
//        log.info(req);
//        String accessToken=(String)accessTokentool.getNewAccessToken().get("rs");
        //todo  获取素材列表

        InputStream inst=req.getInputStream();
        Map map=WeiChatUtil.xmlToMap(inst);
        log.info("FromUserName="+map.get("FromUserName"));
        log.info("Content="+map.get("Content"));
        log.info("MsgType="+map.get("MsgType"));
        log.info("PicUrl="+map.get("PicUrl"));
        log.info("MediaId="+map.get("MediaId"));
        Map mapres=new HashMap();
        mapres.put("FromUserName", map.get("ToUserName"));
        mapres.put("ToUserName", map.get("FromUserName"));
        mapres.put("Content", "我的大学我的城");
        mapres.put("MsgType", "text");
        mapres.put("CreateTime", 12455744);
        return WeiChatUtil.MapToXml(mapres);
    }
    //主页
    @RequestMapping("index")
    public void toindex(HttpServletRequest req, HttpServletResponse res ) throws IOException{
        String code=req.getParameter("code");
        String companyid=req.getParameter("c");
        HashMap<String,String> rs=WeiChatUtil.getOpenIdAndToken(code, WeiChatConfig.appid,WeiChatConfig.secretid);
        String openId=rs.get("openId");
        String access_token=rs.get("access_token");
        req.getSession().setAttribute("openId", rs.get("openId"));
        log.info("v2----code=="+code+" ---openId=="+openId+"---access_token---"+access_token);

        res.sendRedirect("http://zwh.3kkk.xyz/blog/index.html?openid="+openId+"&bizId="+companyid);
    }

    //主页
    @RequestMapping("about")
    public void toabout(HttpServletRequest req, HttpServletResponse res ) throws IOException{
        String code=req.getParameter("code");
        String companyid=req.getParameter("c");
        HashMap<String,String> rs=WeiChatUtil.getOpenIdAndToken(code, WeiChatConfig.appid,WeiChatConfig.secretid);
        String openId=rs.get("openId");
        String access_token=rs.get("access_token");
        req.getSession().setAttribute("openId", rs.get("openId"));
        log.info("v2----code=="+code+" ---openId=="+openId+"---access_token---"+access_token);

        res.sendRedirect("http://zwh.3kkk.xyz/blog/about.html?openid="+openId+"&access_token="+access_token);
    }

    //主页
    @RequestMapping("friends")
    public void tofriends(HttpServletRequest req, HttpServletResponse res ) throws IOException{
        String code=req.getParameter("code");
        String companyid=req.getParameter("c");
        HashMap<String,String> rs=WeiChatUtil.getOpenIdAndToken(code, WeiChatConfig.appid,WeiChatConfig.secretid);
        String openId=rs.get("openId");
        String access_token=rs.get("access_token");
        req.getSession().setAttribute("openId", rs.get("openId"));
        log.info("v2----code=="+code+" ---openId=="+openId+"---access_token---"+access_token);

        res.sendRedirect("http://zwh.3kkk.xyz/blog/friends.html?openid="+openId+"&bizId="+companyid);
    }


    @RequestMapping("vmunu")
    public  String createMunu() throws UnsupportedEncodingException {
        WechatMenuUtil.createMenuJinWei(WeiChatConfig.appid,WeiChatConfig.secretid);
        return "done";
    }


    @RequestMapping("v404")
    public void to404(HttpServletRequest req, HttpServletResponse res ) throws IOException{

        res.sendRedirect("/core/404.html");
    }
}
